package bookshop.service.impl;

import java.util.ArrayList;
import java.util.List;

import bookshop.dao.DaoFactory;
import bookshop.dao.OrderDao;
import bookshop.domain.CartItem;
import bookshop.domain.OrderInfo;
import bookshop.domain.OrderItem;
import bookshop.domain.SaleBook;
import bookshop.domain.ShoppingCart;
import bookshop.service.OrderService;
import bookshop.service.helper.OrderQueryHelper;
import bookshop.utils.Page;

public class OrderServiceImpl implements OrderService {

	public void SavaOrderInfo(OrderInfo orderInfo) {
		OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");
		orderDao.AddOrderInfo(orderInfo);
	}

	public void saveAllOrderItem(ShoppingCart cart, String orderId) {
		OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");
		OrderItem orderItem = null;
		for (CartItem item : cart.getItems()) {
			orderItem = new OrderItem();
			orderItem.setBook(item.getBook());
			orderItem.setItemBookAmount(item.getAmount());
			orderItem.setItemBookPrice(item.getBook().getBookPrice());
			orderItem.setOrderId(orderId);
			orderDao.saveOrderItem(orderItem);
		}
	}

	public Page loadOrdersByCondition(OrderQueryHelper helper, Page page) {
		OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");
		page.setTotalRecNum(orderDao.countOrdersByCondition(helper));
		page.setPageContent(orderDao.getScopedOrders(helper,
				page.getStartIndex(), page.getPageSize()));
		return page;
	}

	public List<OrderItem> GetOrderItemByOrderId(String orderId) {
		OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");

		return orderDao.GetOrderItemByOrderId(orderId);

	}

	public void DelOrder(String orderId) {
		OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");
		orderDao.DelOrderItem(orderId);
		orderDao.DelOrder(orderId);
	}

	public void UpdateOrder(OrderInfo orderInfo){
		OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");
		orderDao.UpdateOrder(orderInfo);
	}
	
	public OrderInfo GetOrderByOrderId(String orderId){
		OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");
		return orderDao.GetOrderByOrderId(orderId);
		
		
	}

    public List<SaleBook> GetSaleBook(){
    	OrderDao orderDao = (OrderDao) DaoFactory.getDao("orderDao");
    	List<SaleBook> saleBooks = orderDao.GetSaleBook();
    	
        for(OrderItem item:orderDao.GetSalesBook()){
        	
        	for(SaleBook sale:saleBooks){
        		if(item.getBook().getBookCode().equals(sale.getBook().getBookCode())){
        			sale.setNumber(sale.getNumber()+item.getItemBookAmount());
        		}
        	}
        	
        }
    	
        
    	return saleBooks;
    }
}
